#ifndef __M_BIND_H__
#define __M_BIND_H__
#include "../mqcommon/mq_logger.hpp"
#include "../mqcommon/mq_helper.hpp"
#include "../mqcommon/mq_msg.pb.h"
#include <iostream>
#include <string>
#include <unordered_map>
#include <memory>
#include <mutex>

namespace csjmq
{
    struct Binding
    {
        using ptr = std::shared_ptr<Binding>;
        std::string exchange_name;
        std::string msgqueue_name;
        std::string binding_key;
        Binding(const std::string &ename, const std::string &qname, const std::string &key)
            : exchange_name(ename),
              msgqueue_name(qname),
              binding_key(key)
        {
        }
    };

    // 一个队列对应一个绑定信息，依靠队列名称查找绑定信息
    using MsgQueueBindingMap = std::unordered_map<std::string, Binding::ptr>;
    // 而一个交换机对应很多个队列，这个BindingMap中包含了所有的绑定信息，并且以交换机为单元进行了区分
    using BindingMap = std::unordered_map<std::string, MsgQueueBindingMap>;

    class BindingMapper
    {
    public:
        BindingMapper(const std::string &dbfile) : _sql_helper(dbfile)
        {
            std::string path = FileHelper::parentDirectory(dbfile);
            FileHelper::createDirectory(path);
            assert(_sql_helper.open());
            createTable();
        }

        void createTable()
        {
            // create table if not exists binding_table(exchange_name varchar(32),
            // msgqueue_name varchar(32),  binding_key varchar(128));
            std::stringstream sql;
            sql << "create table if not exists binding_table(";
            sql << "exchange_name varchar(32), ";
            sql << "msgqueue_name varchar(32), ";
            sql << "binding_key varchar(128));";
            _sql_helper.exec(sql.str(), nullptr, nullptr);
        }

        void removeTable()
        {
            // drop table if exists binding_table;
            std::string sql = "drop table if exists binding_table;";
            _sql_helper.exec(sql, nullptr, nullptr);
        }

        bool insert(Binding::ptr &binding)
        {
            // insert into binding_table values('exchange_name', 'msgqueue_name', 'binding_key');
            std::stringstream sql;
            sql << "insert into binding_table values(";
            sql << "'" << binding->exchange_name << "', ";
            sql << "'" << binding->msgqueue_name << "', ";
            sql << "'" << binding->binding_key << "');";
            return _sql_helper.exec(sql.str(), nullptr, nullptr);
        }

        void remove(const std::string &ename, const std::string &qname)
        {
            // delete from binding_table where exchange_name = '' and msgqueue_name = '';
            std::stringstream sql;
            sql << "delete from binding_table where exchange_name = ";
            sql << "'" << ename << "'";
            sql << " and msgqueue_name = ";
            sql << "'" << qname << "';";
            _sql_helper.exec(sql.str(), nullptr, nullptr);
        }

        void removeExchangeBindings(const std::string &ename)
        {
            std::stringstream sql;
            sql << "delete from binding_table where exchange_name = ";
            sql << "'" << ename << "';";
            _sql_helper.exec(sql.str(), nullptr, nullptr);
        }

        void removeQueueBindings(const std::string &qname)
        {
            std::stringstream sql;
            sql << "delete from binding_table where msgqueue_name = ";
            sql << "'" << qname << "';";
            _sql_helper.exec(sql.str(), nullptr, nullptr);
        }

        BindingMap recovery()
        {
            BindingMap result;
            std::string sql = "select exchange_name, msgqueue_name, binding_key from binding_table;";
            _sql_helper.exec(sql, selectCallback, &result);
            return result;
        }
        static int selectCallback(void *arg, int col_count, char **row, char **fields)
        {
            BindingMap *result = (BindingMap *)arg;
            Binding::ptr bp = std::make_shared<Binding>(row[0], row[1], row[2]);
            // 为了防止 交换机相关的绑定信息已经存在，因此不能直接创建队列映射，进行添加，这样会覆盖历史数据
            // 因此得先获取交换机对应的映射对象，往里边添加数据
            // 但是，若这时候没有交换机对应的映射信息，因此这里的获取要使用引用（会保证不存在则自动创建）
            MsgQueueBindingMap &qmap = (*result)[bp->exchange_name];
            qmap.insert(std::make_pair(bp->msgqueue_name, bp));
            return 0;
        }

    private:
        SqliteHelper _sql_helper;
    };

    class BindingManager
    {
    public:
        using ptr = std::shared_ptr<BindingManager>;
        BindingManager(const std::string dbfile) : _mapper(dbfile)
        {
            _bindings = _mapper.recovery();
        }

        bool bind(const std::string &ename, const std::string &qname,
                  const std::string &key, bool durable)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            auto it = _bindings.find(ename);
            // 如果绑定信息已经存在了，直接返回真
            if (it != _bindings.end() && it->second.find(qname) != it->second.end())
            {
                return true;
            }
            // _mapper是否需要持久化，看的是交换机是否需要持久化以及队列是否需要持久化
            Binding::ptr bp = std::make_shared<Binding>(ename, qname, key);
            if (durable == true)
            {
                bool ret = _mapper.insert(bp);
                if (ret == false)
                    return false;
            }
            auto &qbmap = _bindings[ename];
            qbmap.insert(std::make_pair(qname, bp));
            return true;
        }

        bool unbind(const std::string &ename, const std::string &qname)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            auto eit = _bindings.find(ename);
            if (eit == _bindings.end())
                return false;
            auto qit = eit->second.find(qname);
            if (qit == eit->second.end())
                return false;
            _mapper.remove(ename, qname);
            _bindings.erase(ename);
            return true;
        }

        void removeExchangeBindings(const std::string &ename)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _mapper.removeExchangeBindings(ename);
            _bindings.erase(ename);
        }

        void removeQueueBindings(const std::string &qname)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            // 先删除表中的队列绑定信息
            _mapper.removeQueueBindings(qname);
            // 然后遍历所有的交换机，删除与该队列的绑定信息
            for (auto start = _bindings.begin(); start != _bindings.end(); start++)
            {
                start->second.erase(qname);
            }
        }

        MsgQueueBindingMap getExchangeBindings(const std::string &ename)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            auto eit = _bindings.find(ename);
            if (eit == _bindings.end())
                return MsgQueueBindingMap();
            return eit->second;
        }

        Binding::ptr getBinding(const std::string &ename, const std::string &qname)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            auto eit = _bindings.find(ename);
            if (eit == _bindings.end())
                return Binding::ptr();
            auto qit = eit->second.find(qname);
            if (qit == eit->second.end())
                return Binding::ptr();

            return qit->second;
        }

        size_t size()
        {
            std::unique_lock<std::mutex> lock(_mutex);
            size_t total_size = 0;
            for (auto start = _bindings.begin(); start != _bindings.end(); start++)
            {
                total_size += (start->second.size());
            }
            return total_size;
        }

        bool exists(const std::string &ename, const std::string &qname)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            auto eit = _bindings.find(ename);
            if (eit == _bindings.end())
                return false;
            auto qit = eit->second.find(qname);
            if (qit == eit->second.end())
                return false;
            return true;
        }

        void clear()
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _mapper.removeTable();
            _bindings.clear();
        }

    private:
        std::mutex _mutex;
        BindingMapper _mapper;
        BindingMap _bindings;
    };
}
#endif
